#include "aht20.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_gpio.h"
#include "hi_io.h"
#include "hi_i2c.h"
#include "hi_errno.h"
#include "globalvars.h"

float g_temp = 0.0; //温度
float g_humi = 0.0; //湿度

int g_temp_flag = 0; //温度大小标志
int g_humi_flag = 0; //湿度大小标志

void Aht20_task()
{
    uint32_t retval = 0;

    hi_io_set_func(HI_IO_NAME_GPIO_13, HI_IO_FUNC_GPIO_13_I2C0_SDA);
    hi_io_set_func(HI_IO_NAME_GPIO_14, HI_IO_FUNC_GPIO_14_I2C0_SCL);

    hi_i2c_init(HI_I2C_IDX_0, 400*1000);
    retval = AHT20_Calibrate();
    printf("AHT20_Calibrate: %d\r\n", retval);

    while (1) {
        retval = AHT20_StartMeasure();
        printf("AHT20_StartMeasure: %d\r\n", retval);

        retval = AHT20_GetMeasureResult(&g_temp, &g_humi);
        if(g_temp > 30.0)
        {
            g_temp_flag = 1;
        }
        else
        {
            g_temp_flag = 0;
        }
        if(g_humi > 75.0)
        {
            g_humi_flag = 1;
        }
        else
        {
            g_humi_flag = 0;
        }
        printf("AHT20_GetMeasureResult: %d, temp = %.2f, humi = %.2f\r\n", retval, g_temp, g_humi);

        sleep(3);
    }
}

void Aht20_entry(void)
{
    usleep(3*1000*1000);  //延时3S

    osThreadAttr_t attr;  //任务属性的结构体

    attr.name = "Aht20_task";   //任务名称
    attr.stack_size = 1024;  //任务的内存大小
    attr.priority = 25;        //任务的优先级

    //创建任务
    if (osThreadNew((osThreadFunc_t)Aht20_task, NULL, &attr) == NULL) 
    {
        //任务创建失败
        printf("  Failed to create Wifi_task!\r\n");
    }
    //任务创建成功
    printf("  Succeed to create Wifi_task!\r\n");
}

SYS_RUN(Aht20_entry);